<template>
  <div class="receipt-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="会员ID">
          <el-input v-model="searchForm.memberId" placeholder="请输入会员ID" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" :value="0" />
            <el-option label="已审核" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">总收款金额</div>
            <div class="stats-value">¥{{ stats.totalAmount || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">本月收款</div>
            <div class="stats-value">¥{{ stats.monthlyAmount || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">待审核</div>
            <div class="stats-value">{{ stats.pendingCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">已审核</div>
            <div class="stats-value">{{ stats.approvedCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">收款单管理</div>
        <div class="table-actions">
          <el-button type="primary" @click="handleAdd">新增收款单</el-button>
          <el-button type="success" @click="handleBatchApprove" :disabled="!selectedIds.length">
            批量审核
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedIds.length">
            批量删除
          </el-button>
          <el-button @click="handleExport">导出</el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="Array.isArray(tableData) ? tableData : []"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="billNo" label="单据编号" width="150" />
        <el-table-column prop="memberId" label="会员ID" width="120" />
        <el-table-column prop="amount" label="收款金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="billDate" label="单据日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.billDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建日期" width="140">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              v-if="row.status === 0"
              type="success"
              size="small"
              @click="handleApprove(row)"
            >
              审核
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增收款单' : dialogType === 'edit' ? '编辑收款单' : '查看收款单'"
      width="600px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :append-to-body="true"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <el-form-item label="单据编号" prop="billNo">
          <el-input v-model="form.billNo" placeholder="请输入单据编号">
            <template #append>
              <el-button @click="generateBillNo" :disabled="dialogType === 'view'">自动生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="会员ID" prop="memberId">
          <el-input v-model="form.memberId" placeholder="请输入会员ID" type="number" />
        </el-form-item>
        <el-form-item label="收款金额" prop="amount">
          <el-input-number
            v-model="form.amount"
            :precision="2"
            :step="100"
            :min="0"
            style="width: 100%"
            placeholder="请输入收款金额"
          />
        </el-form-item>
        <el-form-item label="单据日期" prop="billDate">
          <el-date-picker
            v-model="form.billDate"
            type="date"
            placeholder="请选择单据日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="待审核" :value="0" />
            <el-option label="已审核" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getReceiptList, addReceipt, updateReceipt, deleteReceipt, approveReceipt, batchDeleteReceipt, batchApproveReceipt, exportReceipt, getReceiptStats } from '@/api/finance/receipt'

console.log('收款单组件开始加载...')

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedIds = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add') // add, edit, view
const formRef = ref(null)
const stats = reactive({
  totalAmount: '0.00',
  monthlyAmount: '0.00',
  pendingCount: 0,
  approvedCount: 0
})

// 统计数据
const totalReceipt = ref(0)

// 表单数据
const form = reactive({
  id: null,
  billNo: '',
  memberId: '',
  amount: 0,
  billDate: '',
  status: 0,
  remark: ''
})

// 表单验证规则
const rules = {
  billNo: [{ required: true, message: '请输入单据编号', trigger: 'blur' }],
  memberId: [{ required: true, message: '请输入会员ID', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入收款金额', trigger: 'blur' }],
  billDate: [{ required: true, message: '请选择单据日期', trigger: 'change' }]
}

// 搜索表单
const searchForm = reactive({
  memberId: '',
  status: '',
  dateRange: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    
    console.log('请求参数:', params)
    const response = await getReceiptList(params)
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      const page = response.data
      tableData.value = page?.records || []
      pagination.total = page?.total || 0
    } else if (response && response.records) {
      // 直接Page格式（兼容性）
      tableData.value = response.records || []
      pagination.total = response.total || 0
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
      tableData.value = []
      pagination.total = 0
    }
    
    console.log('数据加载成功，共', tableData.value.length, '条记录')
  } catch (error) {
    console.error('获取收款单数据失败:', error)
    ElMessage.error(`获取数据失败: ${error.message}`)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const loadStats = async () => {
  try {
    const response = await getReceiptStats({})
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      const statsData = response.data
      const totalAmount = parseFloat(statsData?.totalAmount || 0)
      
      Object.assign(stats, {
        totalAmount: totalAmount.toFixed(2),
        monthlyAmount: '0.00',
        pendingCount: 0,
        approvedCount: parseInt(statsData?.totalCount || 0)
      })
      
      // 更新totalReceipt变量
      totalReceipt.value = totalAmount
    } else if (response && response.totalAmount !== undefined) {
      // 直接数据格式（兼容性）
      const totalAmount = parseFloat(response.totalAmount || 0)
      
      Object.assign(stats, {
        totalAmount: totalAmount.toFixed(2),
        monthlyAmount: '0.00',
        pendingCount: 0,
        approvedCount: parseInt(response.totalCount || 0)
      })
      
      // 更新totalReceipt变量
      totalReceipt.value = totalAmount
    } else {
      console.error('统计数据响应格式错误:', response)
      Object.assign(stats, {
        totalAmount: '0.00',
        monthlyAmount: '0.00',
        pendingCount: 0,
        approvedCount: 0
      })
      
      // 重置totalReceipt变量
      totalReceipt.value = 0
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    Object.assign(stats, {
      totalAmount: '0.00',
      monthlyAmount: '0.00',
      pendingCount: 0,
      approvedCount: 0
    })
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
  loadStats()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    memberId: '',
    status: '',
    dateRange: []
  })
  pagination.current = 1
  loadData()
  loadStats()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增
const handleAdd = async () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
  // 自动生成单据编号
  await generateBillNo()
}

// 查看
const handleView = (row) => {
  dialogType.value = 'view'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条收款单吗？', '提示', {
      type: 'warning'
    })
    
    const response = await deleteReceipt(row.id)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success('删除成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除收款单失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 审核
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定要审核这条收款单吗？', '提示', {
      type: 'warning'
    })
    
    const response = await approveReceipt(row.id)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success('审核成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核收款单失败:', error)
      ElMessage.error('审核失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的收款单')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条收款单吗？`, '提示', {
      type: 'warning'
    })
    
    const response = await batchDeleteReceipt(selectedIds.value)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success('批量删除成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除收款单失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 表单提交
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    let response
    if (dialogType.value === 'add') {
      response = await addReceipt(form)
    } else {
      response = await updateReceipt(form)
    }
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
      dialogVisible.value = false
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '提交失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    billNo: '',
    memberId: '',
    amount: 0,
    billDate: '',
    status: 0,
    remark: ''
  })
}

// 自动生成单据编号
const generateBillNo = async () => {
  try {
    // 获取当前日期
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const dateStr = `${year}${month}${day}`
    
    // 获取今天的单据数量作为序号
    const today = `${year}-${month}-${day}`
    const params = {
      pageNum: 1,
      pageSize: 1000,
      startDate: today,
      endDate: today
    }
    
    const page = await getReceiptList(params)
    const todayRecords = page?.records || []
    const todayCount = todayRecords.length + 1
    const sequence = String(todayCount).padStart(3, '0')
    // 生成单据编号：SRK + 年月日 + 3位序号
    const billNo = `SRK${dateStr}${sequence}`
    form.billNo = billNo
    ElMessage.success('单据编号生成成功')
  } catch (error) {
    console.error('生成单据编号失败:', error)
    // 如果出错，使用时间戳作为序号
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const dateStr = `${year}${month}${day}`
    const timestamp = Date.now().toString().slice(-3)
    const billNo = `SRK${dateStr}${timestamp}`
    form.billNo = billNo
    ElMessage.success('单据编号生成成功')
  }
}

// 批量审核
const handleBatchApprove = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要审核的收款单')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要审核选中的 ${selectedIds.value.length} 条收款单吗？`, '提示', {
      type: 'warning'
    })
    
    const response = await batchApproveReceipt(selectedIds.value)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success('批量审核成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '批量审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量审核收款单失败:', error)
      ElMessage.error('批量审核失败')
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    // 检查是否有数据可以导出
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出收款单数据，请稍候...')
    
    // 准备CSV数据
    const headers = ['单据编号', '会员ID', '金额', '单据日期', '状态', '备注']
    const dataList = []
    
    // 添加数据行
    tableData.value.forEach(row => {
      dataList.push([
        row.billNo || '',
        row.memberId || '',
        row.amount || 0,
        row.billDate || '',
        getStatusText(row.status),
        row.remark || ''
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      totalReceipt.value || 0,
      '',
      `记录数: ${pagination.total || 0}`,
      ''
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `收款单数据_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出收款单失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

// 工具函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d)) return String(date).slice(0, 10)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已审核',
    2: '已拒绝'
  }
  return statusMap[status] || '未知'
}

// 初始化
onMounted(() => {
  console.log('收款单组件已挂载，开始初始化...')
  try {
    loadData()
    loadStats()
  } catch (error) {
    console.error('初始化失败:', error)
  }
})
</script>

<style scoped>
.receipt-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-item {
  padding: 10px;
}

.stats-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #67c23a;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 